/*

	- Libreria di funzioni generali -

	Copyright (C) <2010>  SISI Software S.n.c.

	http://www.sisisoftware.it - info@sisisoftware.it

	Questo file è stato sviluppato dalla SISI Software
	la quale ne rivendica tutti i diritti intellettuali.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
*/
package sisi;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Properties;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zul.Decimalbox;
import org.zkoss.zul.Messagebox;


public class General {
	
	public static double round(double value, int places) {
	    if (places < 0) throw new IllegalArgumentException();

	    BigDecimal bd = new BigDecimal(value);
	    bd = bd.setScale(places, RoundingMode.HALF_UP);
	    return bd.doubleValue();
	}

	protected static SimpleDateFormat dateFormat = new SimpleDateFormat(
			"dd/MM/yyyy");
	
	protected static SimpleDateFormat dateOraFormat = new SimpleDateFormat(
	"dd/MM/yyyy HH:mm:ss");
	
	protected static SimpleDateFormat dateOraSenzaSecondiFormat = new SimpleDateFormat(
	"dd/MM/yyyy HH:mm");

	protected static SimpleDateFormat oraFormat = new SimpleDateFormat(
	"HH:mm");

	
	public static String formatoFecha(java.sql.Date sqlDate) {
		if (sqlDate == null) {
			return "";
		} else {
			return dateFormat.format(sqlDate);
		}
	}
	
	public static String formatoFecha(java.util.Date data) {
		if (data == null) {
			return "";
		} else {
			return dateFormat.format(data);
		}
	}
	
	
	public static String formatoFecha(Timestamp data) {
		if (data == null) {
			return "";
		} else {
			return dateFormat.format(data);
		}
	}
	
	public static String formatoFechaOra(Timestamp data) {
		if (data == null) {
			return "";
		} else {
			return dateOraSenzaSecondiFormat.format(data);
		}
	}
	
	public static String formatoOra(Timestamp data) {
		if (data == null) {
			return "";
		} else {
			return oraFormat.format(data);
		}
	}

	public static String formatoOra(java.util.Date date) {
		if (date == null) {
			return "";
		} else {
			return oraFormat.format(date);
		}
	}

	
	
	public static String formatoFechaOra(java.util.Date date) {
		if (date == null) {
			return "";
		} else {
			return dateOraFormat.format(date);
		}
	}
	
	public static String formatoFechaOraSenzaSecondi(java.util.Date date) {
		if (date == null) {
			return "";
		} else {
			return dateOraSenzaSecondiFormat.format(date);
		}
	}
	
	
	public static String formatoFechaOraSenzaSecondi(java.sql.Date sqlDate) {
		if (sqlDate == null) {
			return "";
		} else {
			return dateOraSenzaSecondiFormat.format(sqlDate);
		}
	}
	

	// protected static java.util.Calendar miFecha = null;

	@SuppressWarnings({ "deprecation", "unused" })
	public static java.sql.Date date2Sql(java.util.Date dataDate) {

		if (dataDate == null) {
			return new java.sql.Date(0);
		}

		// get a calendar using the default time zone and locale.
		java.util.Calendar miFecha = Calendar.getInstance();

		// set Date, year, month, date
		if (dataDate != null) {
			miFecha.set(Calendar.YEAR, dataDate.getYear() + 1900);
			miFecha.set(Calendar.MONTH, dataDate.getMonth());
			miFecha.set(Calendar.DATE, dataDate.getDate());
		} else {
			miFecha.set(Calendar.YEAR, 1900);
			miFecha.set(Calendar.MONTH, 0);
			miFecha.set(Calendar.DATE, 0);
		}

		// normalize the object
		miFecha.set(Calendar.HOUR_OF_DAY, 0);
		miFecha.set(Calendar.MINUTE, 0);
		miFecha.set(Calendar.SECOND, 0);
		miFecha.set(Calendar.MILLISECOND, 0);

		// miFecha.set(dataDate.getYear(), dataDate.getMonth(),
		// dataDate.getDate());
		java.sql.Date sqlDate = new java.sql.Date(miFecha.getTime().getTime());

		return sqlDate;

	}
	
	
	public static String limitaString(String valore, int limiteMassimo){
		valore = (valore==null?"":valore);
		valore = valore.trim();
		valore = (valore.length()>limiteMassimo?valore.substring(0,limiteMassimo-1):valore);
		return valore;
	}
	
	@SuppressWarnings("static-access")
	public static BigDecimal stringVirgola2BigDecimal(String valore){
		valore = (valore==null?"":valore);
		valore = soloNumeri(valore);
		valore = valore.trim();
		valore = valore.replace(".", "");
		valore = valore.replace(",", ".");
		
		// prendo 3 numeri dopo il punto
		if (valore.contains(".")){
			int quanti = valore.length()-valore.substring(0, valore.indexOf(".")).length();
			valore = valore.substring(0, valore.indexOf(".")+Math.min(4, quanti));
		}
		//System.out.println(valore);
		BigDecimal valore2 = new BigDecimal(valore);
		valore2.setScale(2, valore2.ROUND_HALF_EVEN);
		return valore2;
	}
	
	private static String soloNumeri(String valore){
		for (int i = valore.length(); i > 0; i--) {
			String tmpVal = valore.substring(i-1, i);
			if (!"0123456789,.-".contains(tmpVal)){
				valore = valore.substring(0, i-1);
			}
		}
		return valore;
	}
	
	public static java.sql.Timestamp date2SqlTimestamp(java.util.Date dataDate) {

		if (dataDate == null) {
			return new java.sql.Timestamp(0);
		}

		java.sql.Timestamp sqlDate = new java.sql.Timestamp(dataDate.getTime());

		return sqlDate;

	}
	

	/**
	 * Pads a String <code>s</code> to take up <code>n</code> characters,
	 * padding with char <code>c</code> on the left (<code>true</code>) or on
	 * the right (<code>false</code>). Returns <code>null</code> if passed a
	 * <code>null</code> String.
	 **/
	public static String paddingString(String s, int n, char c,
			boolean paddingLeft) {
		if (s == null) {
			//return s;
			s = "";
		}

		// PGF, tronca la stringa se più lunga del valore a riempire. 8/3/2010
		if (s.length() > n) {
			s = s.substring(0, n);
			return s;
		}

		int add = n - s.length(); // may overflow int size... should not be a
		// problem in real life
		if (add <= 0) {
			return s;
		}
		StringBuffer str = new StringBuffer(s);
		char[] ch = new char[add];
		Arrays.fill(ch, c);
		if (paddingLeft) {
			str.insert(0, ch);
		} else {
			str.append(ch);
		}
		return str.toString();
	}


	public static String padLeft(String s, int n){
		return paddingString(s, n, ' ', true);
	}
	

		
	public static String paddingStringJDK( String s, int n, char padd, boolean left){
		
		if (s == null) {
			s = "";
			s = paddingString(s, n, padd, left);
		} else if (s.length()>n){
			s = s.substring(0, n);
		} else if (left){
			s = String.format("%"+n+"s", s).replace(' ', padd);
		} else {
			s = String.format("%-"+n+"s", s).replace(' ', padd);
		}
		
		return s;
	}

	static public String decimalFormat(String pattern, double value) {
		DecimalFormat myFormatter = new DecimalFormat(pattern);
		String output = myFormatter.format(value);
		// System.out.println(value + "  " + pattern + "  " + output);
		return output;
	}

	static public String decimalFormat(String pattern, BigDecimal value) {
		DecimalFormat myFormatter = new DecimalFormat(pattern);
		value = (value==null?BigDecimal.ZERO:value);
		String output = myFormatter.format(value.doubleValue());
		return output;
	}

	public class MyDecimalbox extends Decimalbox {

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		protected Object coerceFromString(String value) {
			if (value != null && value.length() <= 0)
				value = "0";
			value = value.replace(".", ",");
			return super.coerceFromString(value);
		}
	}
		
	public String versione(){
		Properties prop = new Properties();
		String versione=""; 
	    try {
	    	
			//String percorso = Executions.getCurrent().getDesktop().getWebApp().getRealPath("/");
	        //prop.load(new FileInputStream("build_info.properties"));
	        prop.load(getClass().getResourceAsStream("build_info.properties"));	        
	        versione += prop.getProperty("build.major.number")+".";
	        versione += prop.getProperty("build.minor.number")+".";
	        versione += prop.getProperty("build.revision.number")+" ";
	        versione += "("+prop.getProperty("build.data.number")+")";

	    } catch (IOException e) {
	    }
        return versione;
	}

	
	public static String ConvertoNomeFile( String nomeFile){
		
		String carValidi = "0123456789abcdefghijklmnopqrstuvwxyz.ABCDEFGHIJKLMNOPQRSTUVWXYZ -_";
		nomeFile = (nomeFile == null?"":nomeFile);
		nomeFile = nomeFile.replace("à", "a");
		nomeFile = nomeFile.replace("è", "e");
		nomeFile = nomeFile.replace("é", "e");
		nomeFile = nomeFile.replace("ì", "i");
		nomeFile = nomeFile.replace("ò", "o");
		nomeFile = nomeFile.replace("ù", "u");
		for (int i = 0; i < nomeFile.length(); i++) {
			String tmpVal = nomeFile.substring(i, i+1);
			if (!carValidi.contains(tmpVal)){
				nomeFile = nomeFile.replace(tmpVal, "-");
			}
		}
		return nomeFile;
	}

	public static String TolgoAccenti( String s){
		s = (s == null?"":s);
		s = s.replace("à", "a");
		s = s.replace("è", "e");
		s = s.replace("é", "e");
		s = s.replace("ì", "i");
		s = s.replace("ò", "o");
		s = s.replace("ù", "u");
								
		return s;
	}
	
	public static String TolgoLettereMinusculo( String s){
		String[] lettere = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
		for (String lettera : lettere) {
			s = s.replace(lettera, "");
		}
								
		return s;
	}
	
	public Boolean lInLocale(){
		boolean lInLocale = false;
		String domainName = Executions.getCurrent().getServerName();

		// se lavoriamo in localhost o in rete locale, nel nostro caso 192.x.x.x
		if (domainName.equals("localhost")
				|| domainName.substring(0, 3).equals("192")
				|| domainName.substring(0, 3).equals("10.")) {
			lInLocale = true;
		} else {
			lInLocale = false;
		}		
		
		return lInLocale;
	}
	
	public static String trimNull(String string){
		String s = "";
		s = (string==null?s:string.trim());
		return s;
	}


	public static String toUpperAncheNull(String string){
		String s = "";
		s = (string==null?s:string.toUpperCase());
		return s;
	}
	
	public static void showNotify(String msg, Component ref) {
        Clients.showNotification(msg, "info", ref, "middle_center", 2000);
    }


	public static void showNotify(String msg, Component ref, Integer time) {
		time = (time==null?2000:time);
        Clients.showNotification(msg, "info", ref, "middle_center", time);
    }

	public static void showNotify(String msg, Component ref, Integer time, String type) {
		time = (time==null?2000:time);
		type = (type==null?"info":type);
        Clients.showNotification(msg, type, ref, "middle_center", time);
    }

	
	public void MsgBox(String cTxt, String cTitle) {
		if (cTitle == null || cTitle.isEmpty()) {
			cTitle = "Information"; 
		}
		Messagebox
				.show(cTxt, cTitle, Messagebox.OK, Messagebox.INFORMATION);
	}
	
	
	public void errorBox(String cTxt, String cTitle) {
		if (cTitle == null || cTitle.isEmpty()) {
			cTitle = "Error";
		}
		Messagebox
				.show(cTxt, cTitle, Messagebox.OK, Messagebox.ERROR);
	}

	
	
	
	
	// percorso di alcuni files: locale o sul server
	
	public String percorsoFincati() {
		return percorsoFiles("reports", "fincati");
	}

	public String percorsoImg() {
		return percorsoFiles("img", "immagini");
	}
	

	public String percorsoEsporta() {
		return percorsoFiles("esporta", "esporta");
		//return "/Users/Shared";
	}
	
	public String percorsoFiles(String folder, String folder2) {
		boolean lInLocale = lInLocale();
		String domainName = Executions.getCurrent().getServerName();
		String percorso;

		if (lInLocale) {

			percorso = Executions.getCurrent().getDesktop().getWebApp()
					.getRealPath("/" + folder);

		} else {
			//String database = (String)Executions.getCurrent().getDesktop().getSession().getAttribute("Database"); // user.substring(0, user.indexOf(".") );
			
			String database = "pico";
			
			// plesk con tomcat5
			//percorso = "/usr/share/tomcat5/psa-webapps/" + domainName + "/dati/" + database + "/" + folder2;
			
			//plesk con tomcat6
			percorso = "/usr/share/tomcat6/psa-webapps/" + domainName + "/dati/" + (database==null?"":database) + "/" + folder2;
			
		}

		return percorso; 
	}
	
	public String percorsoLogoIndex(){
		String percorso = percorsoFiles("img", "");
		for (int i = 0; i < 5; i++) {
			if ( percorso.endsWith("/") ){
				percorso = percorso.substring(0, percorso.length()-1 );				
			} else {
				break;
			}
		}
		percorso = percorso + "/";
		return percorso;
	}

	
	public static Double doubleZeroNull(Double valore){
		return (valore==null?0.00:valore);
	}
	

	public static Integer integerZeroNull(Integer valore){
		return (valore==null?0:valore);
	}
	
	
}